package com.zrf.base.knowledge.sign;

import org.apache.commons.codec.binary.Hex;

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

public class EccTest {
    /**
     * KEY_ALGORITHM
     */
    private static final String KEY_ALGORITHM = "EC";

    public static void main(String[] args) throws Exception {
        //verifySign("我是签名内容","04fe8bb2f4ade8b70df5317a5cb75def4",
        String data = "我是签名内容";
        String sign = "3045022100e122c7dac9e91a739b9d05efe98a6df6008130ef3846a1158585da37af06cd0502207c96183e051146c94bd5f9931bd62308092c7dca7da0966187e0185be2c635e1";
        String test = "3056301006072a8648ce3d020106052b8104000a03420004c3a35ae9102e0d9666e66e3faf8176c30f0e936857a9c322330089dbac373077f775dcf231c24748924e0b5ee8097454f9931607e9404bde71faa77a422b6658";
        String pubkey = "04fe8bb2f4ade8b70df5317a5cb75def45448b2f1266ca34c489a20437d8fff804105ef2a467136a4520c039a77f816a4e19878807e9f4de91a344e95f989c1462";

        test(data,pubkey,sign);
//        testPubKey();
    }


    public static PublicKey getPublicKey(String publicKey) throws Exception{
        ByteBuffer byteBuffer = ByteBuffer.wrap(Hex.decodeHex(publicKey));
        X509EncodedKeySpec spec = new X509EncodedKeySpec(byteBuffer.array());
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        return keyFactory.generatePublic(spec);
    }



    public static boolean test(String data, String pubKey, String sign) throws Exception {
        Signature ecdsaVerify = Signature.getInstance("SHA1withECDSA");

        PublicKey publicKey = getPublicKey(pubKey);

        ecdsaVerify.initVerify(publicKey);
        ecdsaVerify.update(data.getBytes());
        System.out.println(new String(ecdsaVerify.sign()));;
        boolean result = ecdsaVerify.verify(Hex.decodeHex(sign));
        System.out.println(result);
        return result;
    }


}
